#!/usr/bin  python
# _*_ coding:utf-8 _*_
"""
----------------------------------
    File Name: category
    Description:
        Author: lhw
        Date: 2020/6/3
-----------------------------------
"""

from rest_framework import serializers, exceptions
from EducationContent import models
from rest_framework.exceptions import ValidationError
from Common.utils import CommonUtil
from django.db.models import Min, Max


class CategoryModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.EducationCategory
        fields = ("cid", "parent_id", "title", "level", "order_id", "hospital", 'created_at', 'updated_at')

    # def validate_title(self, value):
    #     if not models.EducationCategory.objects.filter(title=value):
    #         return value
    #     raise ValidationError("Already existed category name")

    def validate_cid(self, value):
        if value == "":
            value = CommonUtil.getTimeRandomCode()
            return value
        return value

    def validate_level(self, value):
        if value <= 5:
            return value
        raise ValidationError("our web only support max_level is 5")

    def validate(self, attrs):
        current_max_order = models.EducationCategory.objects.filter(
            hospital_id=attrs['hospital'],
            parent_id=attrs['parent_id']
        ).all().aggregate(Max('order_id'))['order_id__max']
        if current_max_order is None:
            current_max_order = 0
        attrs['order_id'] = current_max_order + 1
        attrs['title_SP'] = attrs['title']
        return attrs
